package com.lancer.cloud.generator.util;

import com.google.common.collect.Lists;
import com.lancer.cloud.common.constants.CharacterConstants;
import com.lancer.cloud.common.constants.PackagePathConstants;
import com.lancer.cloud.generator.model.config.ColumnInfoConfig;
import com.lancer.cloud.generator.model.config.TableInfoConfig;
import com.lancer.cloud.generator.model.dto.BuildConfigDto;
import com.lancer.cloud.generator.model.entity.ColumnInfo;
import com.lancer.cloud.generator.model.entity.TableInfo;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.BeanUtils;

/**
 * 代码生成工具类
 *
 * caijinbang
 * @date 2019-06-16 15:12
 */
public class CodeGeneratorUtil {

    private static Boolean hasBigDecimal = false;

    /**
     * 生成模板的方式
     *
     * @return 模板集合
     */
    public static List<String> getTemplates() {
        List<String> templates = Lists.newArrayList();
        templates.add(PackagePathConstants.MYBATIS_ENTITY_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_MAPPERXML_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_MAPPER_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_SERVICE_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_SERVICEIMPL_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_QUERY_TEMPLATE);
        templates.add(PackagePathConstants.MYBATIS_CONTROLLER_TEMPLATE);

        return templates;
    }

    /**
     * 生成代码
     *
     * @param buildConfigDto 构建配置
     * @param tableInfo 表信息
     * @param columns 列信息
     * @param zip 压缩包
     */
    public static void generatorCode(BuildConfigDto buildConfigDto, TableInfo tableInfo,
        List<ColumnInfo> columns, ZipOutputStream zip) {
        hasBigDecimal = false;
        // 配置信息
        Configuration config = getConfig();
        // 表信息
        TableInfoConfig tableConfig = new TableInfoConfig();
        //  配置 包名等配置
        buildTableConfig(buildConfigDto, config, tableConfig);
        BeanUtils.copyProperties(tableInfo, tableConfig);
        //  构建表基本信息
        buildTableInfo(config, tableConfig, columns);
        // 生成代码
        gen(buildConfigDto, tableConfig, zip);


    }

    /**
     * 列名转换成Java属性名
     *
     * @param columnName 列名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'})
            .replace(CharacterConstants.UNDERLINE, CharacterConstants.NULL);
    }

    /**
     * 表名转换成Java类名
     *
     * @param tableName 表名
     * @param tablePrefix 表名前缀
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, CharacterConstants.NULL);
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, TableInfoConfig tableInfoConfig) {
        String packagePath =
            "main" + File.separator + "java" + File.separator + tableInfoConfig.getPackageName()
                .replace(".", File.separator);
        String resourcesPath = "main" + File.separator + "resources";
        String className = tableInfoConfig.getClassName();
        if (template.contains(PackagePathConstants.MYBATIS_ENTITY_TEMPLATE)) {
            return packagePath + File.separator + className + ".java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_QUERY_TEMPLATE)) {
            String path = "main" + File.separator + "java" + File.separator + tableInfoConfig
                .getQueryPackageName().replace(".", File.separator);
            return path + File.separator + className + "Query.java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_MAPPER_TEMPLATE)) {
            String path = "main" + File.separator + "java" + File.separator + tableInfoConfig
                .getMapperPackageName().replace(".", File.separator);
            return path + File.separator + className + "Mapper.java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_SERVICE_TEMPLATE)) {
            String path = "main" + File.separator + "java" + File.separator + tableInfoConfig
                .getServicePackageName().replace(".", File.separator);
            return path + File.separator + className + "Service.java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_SERVICEIMPL_TEMPLATE)) {
            String path = "main" + File.separator + "java" + File.separator + tableInfoConfig
                .getServicePackageName().replace(".", File.separator);
            return path + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_CONTROLLER_TEMPLATE)) {
            String path = "main" + File.separator + "java" + File.separator + tableInfoConfig
                .getControllerPackageName().replace(".", File.separator);
            return path + File.separator + className + "Controller.java";
        }
        if (template.contains(PackagePathConstants.MYBATIS_MAPPERXML_TEMPLATE)) {
            return resourcesPath + File.separator + "mapper" + File.separator + className
                + "Mapper.xml";
        }
        return null;
    }


    /**
     * 构建表配置信息  包名等
     */
    public static void buildTableConfig(BuildConfigDto buildConfigDto, Configuration configuration,
        TableInfoConfig tableInfoConfig) {
        BeanUtils.copyProperties(buildConfigDto, tableInfoConfig);
        if (StringUtils.isEmpty(tableInfoConfig.getPackageName())) {
            tableInfoConfig.setPackageName(configuration
                .getString(PackagePathConstants.ENTITY_CLAZZ_KEY,
                    PackagePathConstants.ENTITY_CLAZZ_VALUE));
        }
        if (StringUtils.isEmpty(tableInfoConfig.getDaoPackageName())) {
            tableInfoConfig.setDaoPackageName(
                configuration.getString(PackagePathConstants.DAO_PACKAGE_NAME_KEY,
                    PackagePathConstants.DAO_PACKAGE_NAME_VALUE));
        }
        if (StringUtils.isEmpty(tableInfoConfig.getControllerPackageName())) {
            tableInfoConfig.setDaoPackageName(configuration
                .getString(PackagePathConstants.CONTROLLER_PACKAGE_NAME_KEY,
                    PackagePathConstants.CONTROLLER_PACKAGE_NAME_VALUE));
        }
        if (StringUtils.isEmpty(tableInfoConfig.getMapperPackageName())) {
            tableInfoConfig.setDaoPackageName(
                configuration.getString(PackagePathConstants.MAPPER_PACKAGE_NAME_KEY,
                    PackagePathConstants.MAPPER_PACKAGE_NAME_VALUE));
        }

        if (StringUtils.isEmpty(tableInfoConfig.getAuthorName())) {
            tableInfoConfig.setAuthorName(configuration
                .getString(PackagePathConstants.AUTHOR_NAME_KEY,
                    PackagePathConstants.AUTHOR_NAME_VALUE));
        }

        if (StringUtils.isEmpty(tableInfoConfig.getServiceApiPackageName())) {
            tableInfoConfig.setServiceApiPackageName(configuration
                .getString(PackagePathConstants.SERVICE_API_PACKAGE_NAME_KEY,
                    PackagePathConstants.SERVICE_API_PACKAGE_NAME_VALUE));
        }

        if (StringUtils.isEmpty(tableInfoConfig.getServicePackageName())) {
            tableInfoConfig.setServicePackageName(
                configuration.getString(PackagePathConstants.SERVICE_PACKAGE_NAME_KEY,
                    PackagePathConstants.SERVICE_PACKAGE_NAME_VALUE));
        }

        if (StringUtils.isEmpty(tableInfoConfig.getQueryPackageName())) {
            tableInfoConfig.setQueryPackageName(
                configuration.getString(PackagePathConstants.QUERY_PACKAGE_NAME_CLAZZ_KEY,
                    PackagePathConstants.QUERY_PACKAGE_NAME_VALUE));
        }

    }

    /**
     * 构建表基本数据信息
     */
    public static void buildTableInfo(Configuration config, TableInfoConfig tableConfig,
        List<ColumnInfo> columns) {
        // 表名转换成Java类名
        String className = tableToJava(tableConfig.getTableName(), config.getString("tablePrefix"));
        tableConfig.setClassName(className);
        tableConfig.setLowerClassName(StringUtils.uncapitalize(className));

        // 列信息
        List<ColumnInfoConfig> columnInfoConfigs = new ArrayList<>();
        for (ColumnInfo column : columns) {
            ColumnInfoConfig columnEntity = new ColumnInfoConfig();
            BeanUtils.copyProperties(column, columnEntity);
            // 列名转换成Java属性名
            String upAttrName = columnToJava(column.getColumnName());
            columnEntity.setUpAttrName(upAttrName);
            String temp = columnEntity.getUpAttrName();
            temp = (new StringBuilder()).append(Character.toLowerCase(temp.charAt(0)))
                .append(temp.substring(1)).toString();
            columnEntity.setAttrName(temp);
            // 列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && StringUtils.equals("BigDecimal", column.getDataType())) {
                hasBigDecimal = true;
            }
            // 是否主键
            if (tableConfig.getPk() == null && StringUtils
                .equalsIgnoreCase("PRI", column.getColumnKey())) {
                tableConfig.setPk(columnEntity);
            }
            columnInfoConfigs.add(columnEntity);
        }
        tableConfig.setColumnInfo(columnInfoConfigs);
        // 没主键，则第一个字段为主键
        if (tableConfig.getPk() == null) {
            tableConfig.setPk(tableConfig.getColumnInfo().get(0));
        }
    }

    /**
     * 生成代码
     */
    public static void gen(BuildConfigDto buildConfigDto, TableInfoConfig tableConfig,
        ZipOutputStream zip) {
        // 设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        LocalDateTime now = LocalDateTime.now();
        // 封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableInfo", tableConfig);
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("datetime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        VelocityContext context = new VelocityContext(map);

        // 获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableConfig)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException("渲染模板失败，表名：" + tableConfig.getTableName(), e);
            }
        }
    }
}
